<template>
  <view class="page">
    <view class="title">我的项目</view>

    <view v-if="loading" class="hint">加载中...</view>
    <view v-else-if="err" class="err">{{ err }}</view>
    <view v-else-if="projects.length === 0" class="hint">暂无数据</view>

    <view v-else>
      <view v-for="p in projects" :key="p.projectId" class="card">
        <view class="row">
          <text class="label">项目名称：</text><text>{{ p.projectName || '-' }}</text>
        </view>
        <view class="row">
          <text class="label">项目地址：</text><text>{{ p.projectAddress || '-' }}</text>
        </view>
        <view class="row">
          <text class="label">施工单位：</text><text>{{ p.constructionUnit || '-' }}</text>
        </view>
<!--        <view class="row">-->
<!--          <text class="label">工程计划时间：</text><text>{{ p.projectSchedule || '-' }}</text>-->
<!--        </view>-->

        <!-- 展示 JSON：成员与子工程 -->
        <view class="row">
          <text class="label">成员编号：</text>
          <text>{{p.memberCodesText}}</text>
        </view>
        <view class="row">
          <text class="label">子工程：</text>
          <text>{{ p.subprojectsText }}</text>
        </view>

        <!-- 可跳详情 -->
        <button class="btn" @click="goDetail(p.projectId)">查看详情</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '@/services/api'



const projects = ref<any[]>([])
const loading = ref(false)
const err = ref('')

function safeParseArray(v: any): string[] {
  if (Array.isArray(v)) return v
  if (typeof v === 'string' && v.trim().startsWith('[')) {
    try { return JSON.parse(v) } catch { /* ignore */ }
  }
  return []
}

const toArray = (v: any): string[] => {
  if (Array.isArray(v)) return v
  if (typeof v === 'string') {
    const s = v.trim()
    if (s.startsWith('[') && s.endsWith(']')) {
      try { return JSON.parse(s) } catch { /* fallthrough */ }
    }
    return s.split(/[,\s，、]+/).filter(Boolean)
  }
  return []
}

// 把后端字段适配成你模板正在使用的字段名，并额外生成可直接渲染的文本
const adaptProject = (p: any) => {
  const memberCodes = toArray(p?.projectMembers)
  const subprojects  = toArray(p?.subprojects)
  return {
    projectId: p?.id ?? '',
    projectName: p?.name ?? '',
    projectAddress: p?.address ?? '',
    constructionUnit: p?.construction ?? '',  // ← 后端是 construction
    memberCodes,
    subprojects,
    // 直接给模板用的文本，避免再调函数
    memberCodesText: memberCodes.length ? memberCodes.join('、') : '-',
    subprojectsText: subprojects.length ? subprojects.join('、') : '-',
    projectInnerNumber: p?.projectInnerNumber ?? ''
  }
}

async function loadMyProjects() {
  loading.value = true
  try {
    const list = await api.getMyProjects()
    console.table(list)               // 看看后端实际字段
    projects.value = (list || []).map(adaptProject)
    console.table(projects.value)     // 应该能看到 constructionUnit / memberCodes / subprojects
  } catch (e:any) {
    err.value = e.message || '加载失败'
  } finally {
    loading.value = false
  }
}

onMounted(loadMyProjects)


// onMounted(async () => {
//   loading.value = true
//   try {
//     const list = await api.getMyProjects()
//     projects.value = list || []
//   } finally {
//     loading.value = false
//   }
// })

// onMounted(async () => {
//   loading.value = true
//   try {
//     const { data } = await api.getMyProjects()
//     projects.value = data || []
//   } catch (e: any) {
//     err.value = e?.response?.data?.message || e?.message || '加载失败'
//   } finally {
//     loading.value = false
//   }
// })
// onMounted(async () => {
//   loading.value = true
//   try {
//     const me = uni.getStorageSync('USER') || {}
//     const code = me?.userCode || me?.user_code || me?.code  // 临时兜底
//     const list = await api.getMyProjectsByUserCode(code)
//     projects.value = list || []
//   } catch (e:any) {
//     err.value = e?.message || '加载失败'
//   } finally {
//     loading.value = false
//   }
// })

function formatJsonArray(jsonStr?: string) {
  if (!jsonStr) return '-'
  try {
    const arr = JSON.parse(jsonStr)
    if (Array.isArray(arr)) return arr.join('、')
    return JSON.stringify(arr)
  } catch {
    return jsonStr
  }
}
//
function formatSubprojects(jsonStr?: string) {
  if (!jsonStr) return '-'
  try {
    const arr = JSON.parse(jsonStr)
    if (Array.isArray(arr)) return arr.map((x: any) => x?.name ?? x).join('、')
    return JSON.stringify(arr)
  } catch {
    return jsonStr
  }
}

function goDetail(id: number) {
  // 你的路由里已有 detail.vue：/pages/projects/detail?id=...
  uni.navigateTo({ url: `/pages/projects/rmc_detail?id=${id}` })
}
</script>

<style scoped>
.page { padding: 12px; }
.title { font-size: 18px; font-weight: 600; margin-bottom: 12px; }
.hint { color: #888; margin-top: 12px; }
.err { color: #d93025; margin-top: 12px; }
.card {
  background: #fff;
  border-radius: 10px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,.06);
}
.row { margin: 4px 0; display: flex; flex-wrap: wrap; }
.label { color: #666; margin-right: 4px; }
.btn { margin-top: 8px; }
</style>
